<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class TaskApplication extends Model
{
    use HasFactory;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'task_id',
        'freelancer_id',
        'tenant_id',
        'application_number',
        'name',
        'phone',
        'email',
        'id_card',
        'gender',
        'birth_date',
        'experience',
        'status',
        'application_note',
        'rejection_reason',
        'review_note',
        'applied_at',
        'processed_at',
        'reviewed_at',
        'processed_by',
        'source',
    ];

    protected $casts = [
        'id'           => 'string',
        'task_id'      => 'string',
        'tenant_id'    => 'string',
        'freelancer_id'=> 'string',
        'processed_by' => 'string',
        'birth_date'   => 'date',
        'applied_at'   => 'datetime',
        'processed_at' => 'datetime',
        'reviewed_at'  => 'datetime',
        'created_at'   => 'datetime',
        'updated_at'   => 'datetime',
    ];

    /**
     * 模型启动时的事件
     */
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function (self $model) {
            if (empty($model->id)) {
                $model->id = self::generateSnowflakeId();
            }
            if (empty($model->application_number)) {
                $model->application_number = 'APP' . date('Ymd') . strtoupper(Str::random(6));
            }
        });
    }

    public static function generateSnowflakeId(): string
    {
        $timestamp = (int) (microtime(true) * 1000);
        $machineId = mt_rand(0, 1023);
        $sequence = mt_rand(0, 4095);

        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;

        return (string) $snowflakeId;
    }

    /**
     * 所属任务
     */
    public function task()
    {
        return $this->belongsTo(Task::class);
    }

    /**
     * 所属租户
     */
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 申请的自由职业者
     */
    public function freelancer()
    {
        return $this->belongsTo(Freelancer::class);
    }

    /**
     * 处理人
     */
    public function processor()
    {
        return $this->belongsTo(TenantUser::class, 'processed_by');
    }

    /**
     * 批准申请
     */
    public function approve($processedBy = null, $note = null)
    {
        $this->update([
            'status' => 'approved',
            'review_note' => $note,
            'processed_at' => now(),
            'reviewed_at' => now(),
            'processed_by' => $processedBy,
        ]);
    }

    /**
     * 拒绝申请
     */
    public function reject($processedBy = null, $reason = null, $note = null)
    {
        $this->update([
            'status' => 'rejected',
            'rejection_reason' => $reason,
            'review_note' => $note,
            'processed_at' => now(),
            'reviewed_at' => now(),
            'processed_by' => $processedBy,
        ]);
    }

    /**
     * 标记离岗
     */
    public function markDimission($processedBy = null, $note = null): void
    {
        $this->update([
            'status' => 'dimission',
            'review_note' => $note,
            'processed_at' => now(),
            'reviewed_at' => now(),
            'processed_by' => $processedBy,
        ]);
    }

    /**
     * 获取状态文本
     */
    public function getStatusText()
    {
        $statusTexts = [
            'pending' => '待审核',
            'approved' => '已通过',
            'rejected' => '已拒绝',
            'cancelled' => '已取消',
        ];

        return $statusTexts[$this->status] ?? '未知状态';
    }

    /**
     * 获取性别文本
     */
    public function getGenderText()
    {
        if ($this->gender === 'male') {
            return '男';
        }

        if ($this->gender === 'female') {
            return '女';
        }

        return '未填写';
    }

    /**
     * 获取学历文本
     */
    public function getEducationText()
    {
        $educationTexts = [
            'high_school' => '高中',
            'college' => '大专',
            'bachelor' => '本科',
            'master' => '硕士',
            'doctor' => '博士',
        ];

        return $educationTexts[$this->education] ?? '未填写';
    }

    /**
     * 获取年龄
     */
    public function getAge()
    {
        if (!$this->birth_date) {
            return null;
        }
        
        return $this->birth_date->diffInYears(now());
    }

    /**
     * 作用域：按状态筛选
     */
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 作用域：按任务筛选
     */
    public function scopeByTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    /**
     * 作用域：按租户筛选
     */
    public function scopeByTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }
}
